<template>
  <div>
    <article-templates :data="articleData">
      <template #article>
        <tdt-map />
        <div>
          <title-card title="动态引入天地图" />
          <pre-code :code="loadTmap" language="JavaScript" />

          <title-card title="初始化天地图" />
          <pre-code :code="initChart" language="JavaScript" />

          <title-card title="关键词查询回调" />
          <pre-code :code="localSearchResult" language="JavaScript" />
        </div>
      </template>
    </article-templates>
  </div>
</template>

<script setup name="Tmap">
import ArticleTemplates from '@/components/ArticleTemplates/index.vue';
import TitleCard from '@/components/TitleCard/index.vue';
import TdtMap from './TdtMap/index.vue';
import { postArticleDetail } from '@/api/home.js';
import { onMounted, ref, toRefs, reactive } from 'vue';

const data = reactive({
  articleData: {},
});
const { articleData } = toRefs(data);

const loadTmap = ref(`const loadTmap = () => {
  try {
      if (T) {
        nextTick(() => {
          initChart();
        });
      }
    } catch (err) {
      loadJs(
        'https://api.tianditu.gov.cn/api?v=4.0&tk=' + tk.value
      ).then((res) => {
        initChart();
      });
    }
}`);
const initChart = ref(`const initChart = () => {
  //初始化地图对象
  map = new T.Map("world-chart");
  console.log(map);
  let center1 = [120.21201, 30.2084];
  if (center.value.length>0) {
    center1 = center.value;
    console.log(1);
    var marker = new T.Marker(new T.LngLat(center.value[0], center.value[1]));
    map.addOverLay(marker);
  }
  //标注
  markspot = new T.MarkTool(map, { follow: true });
  markspot.addEventListener("mouseup", onMorkPolygon);
  //设置显示地图的中心点和级别
  map.centerAndZoom(
    new T.LngLat(center1[0], center1[1]),
    zoom.value
  );
  map.addEventListener("click", (type) => {
    markspot.clear();
    map.clearOverLays();
    markspot.open();
  });

  // 根据关键字搜索建议词
  var config = {
    pageCapacity: 10, //每页显示的数量
    onSearchComplete: localSearchResult, //接收数据的回调函数
  };
  localsearch = new T.LocalSearch(map, config);
}`);
const localSearchResult = ref(`const localSearchResult = (result) => {
  let arr = [];
  if (result.pois) {
    result.pois.forEach((element) => {
      let lonlat = element.lonlat.split(" ");
      arr.push({
        value: element.name,
        district: element.address,
        center: [Number(lonlat[0]), Number(lonlat[1])],
      });
    });
    isPois.value = true;
    pois.value = arr;
  }
}`);

const getTitle = () => {
  postArticleDetail({
    route: 'Tmap',
  }).then((res) => {
    articleData.value = res.data;
  });
};
onMounted(() => {
  getTitle();
});
</script>
